package persistence.category.categoryDAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;

import business.article.entities.Category;

import persistence.DAO.DAOHelper;

public class CategoryDAO {

	

	/**
	 * Singleton implementation begin
	 */
	private static CategoryDAO instance = null;

	private CategoryDAO() {
	}

	public static CategoryDAO getInstance() {
		if (instance == null)
			instance = new CategoryDAO();
		return instance;
	}

	/**
	 * Singleton implementation end
	 * 
	 * @throws badClassException
	 */
	

	public Category[] getCategories() {
		Connection con=null;
		try {
			con=DAOHelper.getInstance().getConnection();
			Statement st=con.createStatement();
			ResultSet r=st.executeQuery(
				  "SELECT name,primary_key FROM Category WHERE primary_key>0");
				  ArrayList<Category> categorias=new ArrayList<Category>();
				  
				  while(r.next()){categorias.add(new Category(r.getString(1), r.getInt(2))); }
				  
				  Category[] ingr=new Category[categorias.size()];
				  categorias.toArray(ingr); return ingr;
				  } catch (SQLException e) { e.printStackTrace();
				  }finally{
						if(con!=null)
							try {
								con.close();
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}	
					}
		
				  return null;
	}

	public void newCategory(String name) {
		Connection con=null;
		try {
			con=DAOHelper.getInstance().getConnection();
			Statement st=con.createStatement();
			st.execute("INSERT INTO Category (name,active,primary_key) VALUES('"
					+ String.valueOf(name)
					+ "',"
					+ "1,"
					+ getNewCategoryID() +")");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(con!=null)
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
		}		
	}
	
	private Integer getNewCategoryID() {
		Connection con=null;
		try {
			con=DAOHelper.getInstance().getConnection();
			Statement st=con.createStatement();
			ResultSet r = st.executeQuery("SELECT primary_key FROM Category");

			ArrayList<Integer> categorias = new ArrayList<Integer>();
			while (r.next()) {
				categorias.add(r.getInt(1));
			}
			
			
			
			if (categorias.size()==0)
				return 1;
			Collections.sort(categorias);
			
			int i = -1;
			for (Integer j : categorias) {
				
				if (i != j)
					break;
				i++;
			}
			return i ;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(con!=null)
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
		}
		return null;
	}
	
}
